export default {
    props: {
        tableHeight: String, //表格高度
        filterRequire: Boolean, //是否必须有筛选项
        showRowIndex: Boolean, //是否显示行号
        emptyText: {
            type: String,
            default: '未能查询到数据'
        }, //未能查询到数据时的显示文本
        pagination: {
            type: Object,
            default: () => ({})
        },
        columns: {
            type: Array,
            default: () => []
        } //自定义传入的列属性
    },
    data() {
        return {
            table: {
                cols: [],
                rows: [],
                pageNo: 1,
                pageSize: 10,
                total: 0,
                loading: false
            }
        }
    },
    computed: {
        isTableEmpty() {
            return this.table.pageNo <= 1 && this.table.rows.length < 1
        }
    },
    inject: {
        dataApi: {
            default: () => {
                throw 'dataApi(inject) is required'
            }
        },
        dataInit: { default: () => rows => rows }
    },
    methods: {
        initTable() {
            this.table.pageNo = this.pagination.pageNo * 1 || 1
            this.table.pageSize = this.pagination.pageSize * 1 || 10
            this.table.total = this.pagination.pageSize * 1 || 0
            this.table.cols = [...this.columns]
        },
        loadTable() {
            if (this.filterRequire && this.isSearchEmpty) {
                return
            }

            this.table.loading = true
            this.getData().then(res => {
                this.table.rows = (res && res.rows) || []
                this.table.total = res.total
            })
        },
        getData(pageNo = this.table.pageNo, pageSize = this.table.pageSize) {
            return this.dataApi({ pageNo, pageSize, ...this.search.value })
                .then(res => ({
                    ...res,
                    rows: this.dataInit(res.rows, this)
                }))
                .catch(err => {
                    this.$message({
                        showClose: true,
                        message: '出错了',
                        type: 'error'
                    })

                    throw err
                })
                .finally(() => {
                    this.table.loading = false
                })
        },
        onCurrentChange(cp) {
            this.table.pageNo = cp
            this.loadTable()
        }
    }
}